
const dbo = require('../utils/db')

var autoid = -1
var autoid_id = null

module.exports = {

    /**
     * 获取当前自增最大值id
     * @returns 
     */
    async get_current_key() {
        const db = await dbo.db_client()
        var shorkey = await db.db().collection("short_key").findOne()
        return shorkey["key_autoid"]
    },
    /**
     * 获取新增id，已做并发获取处理
     * @returns 
     */
    async get_new_key() {
        const db = await dbo.db_client()
        if (autoid == -1) {
            var shorkey = await db.db().collection("short_key").findOne()
            autoid = shorkey["key_autoid"]
            autoid_id = shorkey._id
        }
        var curid = autoid
        autoid = autoid + 1
        await db.db().collection("short_key").updateOne({ _id: autoid_id, key_autoid: { $eq: curid } }, {
            $set: {
                key_autoid: autoid
            }
        })
        return curid
    },
}